有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

随机掷骰的java百分比数学结果不正确

所以我有我正在处理的代码,除了打印/显示百分比结果外,它似乎运行正常。当百分比加起来时,我发现总数加起来不等于100。我觉得这可能与铸造有关,但是,我不知道错误在哪里,我已经多次通过代码。如果有人能帮助我,并给我任何关于结构/任何其他我应该知道的noob东西的提示,请这么做! 我是一个相当新的程序员,有不到半年的时间来做这件事,所以就像我说的,任何提示都将不胜感激。谢谢

import java.util.Random;
import java.util.Scanner;

public class DiceRoller {

    public static void main(String[] args) {
        calculatePercentage();
    }

    //Get roll number from user
    static int getNumOfRolls(){
        Scanner input = new Scanner(System.in);

        System.out.println("How many times would you like to roll the dice?");
        int numOfRolls = input.nextInt();
        return numOfRolls;

    }
    //use object from class random to assign var value from 1 - 6 inclusive
    static int rollDice(){

        Random rand = new Random();
        int die = (rand.nextInt(6) + 1);

        return die;
    }

    static void printPercentage(int[] dieTotal, int numOfRolls){

        double totalPer = 0;
        double percent = 0;

        for(int i = 2; i < dieTotal.length; i++){

            int curNum = dieTotal[i];

            percent = ((curNum / (double)numOfRolls) * 100);
            totalPer += percent;
            System.out.printf("%d was rolled %.2f %% of the time. \n", i, percent);
        }

        System.out.println("Total percentage shown on the screen in: " + totalPer);
    }

    //store values of dice in an array. Call printPercent method defined above.
    static void calculatePercentage(){
        int numOfRolls = getNumOfRolls();

        int die1 = 0;
        int die2 = 0;
        int[] dieTotal = new int[13];

        for(int i = 0; i < numOfRolls - 1; i++){
            die1 = rollDice();
            die2 = rollDice();
            int total = die1 + die2;

            dieTotal[total]++;

        }

        printPercentage(dieTotal, numOfRolls);
    }
}

共 (2) 个答案

  1. # 1 楼答案

    错误出现在calculatePercentage函数中的for循环条件语句中

    因为上限设置为i < numOfRolls -1,所以只能得到n-1个转鼓数。进行以下更改:

    static void calculatePercentage(){
        int numOfRolls = getNumOfRolls();
    
        int die1 = 0;
        int die2 = 0;
        int[] dieTotal = new int[13];
    
        for(int i = 0; i < numOfRolls; i++){
            die1 = rollDice();
            die2 = rollDice();
            int total = die1 + die2;
    
            dieTotal[total]++;
    
        }
    
        printPercentage(dieTotal, numOfRolls);
    }
    
  2. # 2 楼答案

    你掷骰子的次数比要求的少一次。如果你输入3,骰子将只掷两次。原因是for循环条件:

    for(int i = 0; i < numOfRolls - 1; i++){
    

    这将在循环到达2而不是3时停止循环。这是一个“一个接一个”的错误。试试看:

    for(int i = 0; i < numOfRolls; i++){
    

    这给了我:

    Total percentage shown on the screen in: 100.0
    

    请注意,对于numOfRolls的某些值,由于floating-point errors的原因,其加起来可能仍达不到100%。例如53rolls给了我:

    Total percentage shown on the screen in: 99.99999999999999